package com.my.screenadapter.myHandler;

import android.os.Handler;
import android.os.HandlerThread;
import android.os.Looper;
import android.os.Message;
import android.util.Log;
import android.view.View;

import com.my.screenadapter.Base.BaseActivity;
import com.my.screenadapter.R;

import java.util.Random;

public class ThreadHandlerActivity extends BaseActivity {

    private final int threadmethod = 0;
    private final int handlerPost = 1;
    private final int handlerThread = 2;
    Handler customThreadhandler;
    Looper looper;
    private Handler mHandler;
    private HandlerThread mHandlerThread;

    @Override
    protected void init() {
        mHandlerThread = new HandlerThread("upLoadRecordServiceHandlerThread");
        mHandlerThread.start();
        mHandler = new Handler(mHandlerThread.getLooper()) {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                Log.i(TAG, "handleMessage: --- HandlerThread name "+Thread.currentThread().getName());
                switch (msg.what) {
                    case threadmethod:
                        threadMethod();
                        break;

                    case handlerPost:
                        Handler handler = new Handler();
                        handler.postDelayed(new Runnable() {
                            @Override
                            public void run() {
                                Thread thread = Thread.currentThread();
                                Log.i("TTTTTTTTT", thread.getName() + "   " + thread.getId());
                                new Thread(new Runnable() {
                                    @Override
                                    public void run() {
                                        Thread thread3 = Thread.currentThread();
                                        Log.i("TTTT333", thread3.getName() + "   " + thread3.getId());
                                    }
                                }).start();
                            }
                        }, 100);
                        break;
                    case handlerThread:

                        new Thread(new Runnable() {
                            @Override
                            public void run() {
                                try {
                                    Thread.sleep(3000);
                                } catch (InterruptedException e) {
                                    e.printStackTrace();
                                }
                                Thread thread = Thread.currentThread();
                                Log.i("TTTTTTTTT22", thread.getName() + "   " + thread.getId());
                            }
                        }).start();

                        break;
                }
            }
        };
        //以下 类似handlerThread
        new Thread(new Runnable() {
            @Override
            public void run() {
                Looper.prepare();
                Looper looper = Looper.myLooper();
                //将不在接受新的事件加入消息队列  因为消息队列已经退出了
//                looper.quit();//当我们调用Looper的quit方法时，实际上执行了MessageQueue中的removeAllMessagesLocked方法，该方法的作用是把MessageQueue消息池中所有的消息全部清空，无论是延迟消息（延迟消息是指通过sendMessageDelayed或通过postDelayed等方法发送的需要延迟执行的消息）还是非延迟消息。();
//                looper.quitSafely();//当我们调用Looper的quitSafely方法时，实际上执行了MessageQueue中的removeAllFutureMessagesLocked方法，通过名字就可以看出，该方法只会清空MessageQueue消息池中所有的延迟消息，并将消息池中所有的非延迟消息派发出去让Handler去处理，quitSafely相比于quit方法安全之处在于清空消息之前会派发所有的非延迟消息。


                Log.i(TAG, "BBBBBBBB");
                Looper.loop();//todo 写在Looper.loop()之后的代码不会被执行，这个函数内部是一个循环
                Log.i(TAG, "loopppppppppppppppppp");
            }
        }).start();

        Thread methodThread = new Thread(new Runnable() {
            @Override
            public void run() {
                Thread thread = Thread.currentThread();
                Log.i(TAG, thread.getName() + "  id=" + thread.getId());
                while (true) {
                    try {
                        Thread.sleep(10000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                    threadMethod();
                }

            }

        });
        methodThread.start();

        //自定义 线程 +赋值给 handler
        Thread t = new Thread(new Runnable() {
            @Override
            public void run() {
                Thread thread = Thread.currentThread();
                Log.w(TAG, "HHHHHHHHandler" + thread.getName() + "  id=" + thread.getId());
                Looper.prepare();
                looper = Looper.myLooper();
                Looper.loop();
            }
        });
        t.start();
        mHandler.postDelayed(new Runnable() {
            @Override
            public void run() {
                customThreadhandler = new Handler(looper) {
                    @Override
                    public void handleMessage(Message msg) {
                        super.handleMessage(msg);
                        threadMethod();
                    }
                };
            }
        }, 100);


    }

    private void threadMethod() {
        Thread thread = Thread.currentThread();
        Log.i(TAG, thread.getName() + "  id== " + thread.getId() + "   methoddddddddddddd");
    }

    @Override
    protected int initLayoutId() {
        return R.layout.activity_thread_handler;
    }

    public void startThread(View view) {
        mHandler.sendEmptyMessage(threadmethod);
    }

    public void customHandlerThread(View view) {
        customThreadhandler.sendEmptyMessage(0);
    }

    public void threadSleep(View view) {
        //线程崩溃
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Log.i(TAG, "测试线程崩溃。。。。。");
                    try {
                        Thread.sleep(-100);
                    } catch (InterruptedException e) {
                        Log.w(TAG, "线程崩溃了。。。。。");
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "testThreadCrash").start();
    }

    public void threadSleep2(View view) {
        //线程崩溃
        new Thread(new Runnable() {
            @Override
            public void run() {
                while (true) {
                    Log.i(TAG, "测试线程崩溃22。。。。。");
                    try {
                        Thread.sleep(-100);
                    } catch (Exception e) {
                        Log.w(TAG, "线程崩溃了22。。。。。");
                        e.printStackTrace();
                    }
                    try {
                        Thread.sleep(1000);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }
            }
        }, "testThreadCrash22").start();
    }

    public void handlerPost(View view) {
        mHandler.sendEmptyMessage(handlerPost);
        mHandler.sendEmptyMessage(handlerThread);
    }

    private Handler mHandlerByThread;

    public void createLooperInThread(View view) {
        new Thread(new Runnable() {
            @Override
            public void run() {
                Log.i(TAG, "run: ----name "+Thread.currentThread().getName());
                while (true){
                    Looper looper = Looper.myLooper();
                    if (looper == null) {
                        Looper.prepare();
                    }
                    if (mHandlerByThread == null) {
                        mHandlerByThread = new Handler(Looper.myLooper()){
                            @Override
                            public void handleMessage(Message msg) {
                                super.handleMessage(msg);
                                Log.i(TAG, "handleMessage: ---->thread "+msg.what +"  arg"+msg.arg1);
                            }
                        };
                    }
                    Looper.loop();
                    try {
                        Thread.sleep(2);
                    } catch (InterruptedException e) {
                        e.printStackTrace();
                    }
                }

            }
        }).start();
    }

    public void sendToLooperInThread(View view) {
        if (mHandlerByThread != null) {
            Message obtain = Message.obtain();
            int i = new Random().nextInt(10);
            obtain.arg1 =i;
            obtain.what = i+1;
            mHandlerByThread.sendMessage(obtain);
        }
    }
}
